package com.xu.cloud.common.process.support;

import com.xu.cloud.common.constant.CodecConstant;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 字符串HttpInputMessage
 *
 * @author xuguan
 * @since 2025/2/20
 */
public class StringHttpInputMessage implements HttpInputMessage {
    private static final InputStream EMPTY_STREAM = StreamUtils.emptyInput();
    private static final Charset UTF_8 = CodecConstant.UTF_8;
    private final HttpHeaders headers;

    @Nullable
    private final InputStream body;

    public StringHttpInputMessage(HttpHeaders headers, @Nullable String content) throws IOException {
        this.headers = headers;
        if (StringUtils.hasText(content)) {
            this.body = new ByteArrayInputStream(content.getBytes(UTF_8));
        } else {
            this.body = null;
        }
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }

    @Override
    public InputStream getBody() {
        return this.body != null ? body : EMPTY_STREAM;
    }

    public boolean hasBody() {
        return (this.body != null);
    }
}
